package com.zhida.jiyangcenter

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import android.webkit.*
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.manager.app
import chooongg.base.utils.startActivity

import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.utils.GlideEngine
import kotlinx.android.synthetic.main.activity_web_view.*
import java.io.File


@TitleBar(false)
@ContentLayout(R.layout.activity_web_view)
class WebNoTokenActivity : BaseActivity() {
    companion object {
        const val URL = "url"
        const val TITLE = "title"

        const val APP_CACHE_DIRNAME = "/webCache"
    }

    private var mfileChooserParams: WebChromeClient.FileChooserParams? = null
    private var mUploadMessages: ValueCallback<Array<Uri>>? = null

    private var url: String = ""
    private var originalUrl: String = ""

    @SuppressLint("SetJavaScriptEnabled")
    override fun initConfig(savedInstanceState: Bundle?) {

        url = intent.getStringExtra(URL) ?: ""
        originalUrl = url
        title_bar.navigationIcon(R.drawable.iv_back_fill){
            finish()
        }
        view_web.settings.domStorageEnabled = true
        view_web.settings.databaseEnabled = true
        view_web.settings.blockNetworkImage = true
        view_web.settings.setSupportZoom(false)
        view_web.settings.setAppCachePath(app.cacheDir.absolutePath + APP_CACHE_DIRNAME)
        view_web.settings.setAppCacheEnabled(true)

        view_web.settings.databaseEnabled = true
        view_web.settings.setGeolocationEnabled(true)
        view_web.settings.domStorageEnabled = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            view_web.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        view_web.addJavascriptInterface(WebJSInterface(), WebJSInterface.JSName)
        view_web.settings.javaScriptCanOpenWindowsAutomatically = true
        view_web.settings.javaScriptEnabled = true
        view_web.webViewClient = object : WebViewClient() {

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                if (url!!.startsWith("tel:")) {
                    val intent = Intent(Intent.ACTION_VIEW,
                            Uri.parse(url))
                    startActivity(intent)
                } else {
                    view?.loadUrl(url)
                }
                return true
            }

            override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
            }

            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                handler?.proceed()
            }
        }
        view_web.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                if (!title.isNullOrEmpty()) title_bar.title(title)
            }

            override fun onPermissionRequest(request: PermissionRequest?) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) request?.deny()
            }

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress == 100) {
                    view_web.settings.blockNetworkImage = false
                    if (title_bar.getTitle().isNullOrEmpty()) title_bar.title(view?.title ?: "")
                }
            }

            override fun onGeolocationPermissionsShowPrompt(origin: String?, callback: GeolocationPermissions.Callback?) {
                callback?.invoke(origin, true, false)
                super.onGeolocationPermissionsShowPrompt(origin, callback)
            }

            override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?): Boolean {
                mUploadMessages = filePathCallback
                mfileChooserParams = fileChooserParams

                PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .previewImage(true)
                        .isCamera(true)
                        .minimumCompressSize(200)
                        .isZoomAnim(true)
                        .showCropFrame(false)
                        .showCropGrid(false)
                        .isDragFrame(true)
                        .compress(true)
                        .rotateEnabled(true)
                        .scaleEnabled(true)
                        .forResult(999)
                return true
            }

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 999) {
            if (mUploadMessages == null) return
            val selectLists = PictureSelector.obtainMultipleResult(data)
            if (selectLists.isNullOrEmpty()) mUploadMessages!!.onReceiveValue(null) else {
                mUploadMessages!!.onReceiveValue(arrayOf(Uri.fromFile(File(when {
                    !selectLists[0].compressPath.isNullOrEmpty() -> selectLists[0].compressPath
                    !selectLists[0].cutPath.isNullOrEmpty() -> selectLists[0].cutPath
                    !selectLists[0].androidQToPath.isNullOrEmpty() -> selectLists[0].androidQToPath
                    else -> selectLists[0].path
                }))))
            }
            mUploadMessages = null
        }
    }
    override fun initContent(savedInstanceState: Bundle?) {
        view_web.loadUrl(url)
    }

    fun refresh() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view_web.evaluateJavascript("javascript:refreshH5()") {}
        } else view_web.loadUrl("javascript:refreshH5()")
    }

    override fun onResume() {
        super.onResume()
        view_web.onResume()
        refresh()
    }

    override fun onPause() {
        view_web.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        view_web.destroy()
        super.onDestroy()
    }
}